<?php
/**
 * ExaminationType Service.
 * User: Administrator
 * Date: 2020/2/13 0013
 * Time: 下午 2:02
 */
namespace app\api\service\questions;

use app\api\model\questions\Answer;
use app\api\model\questions\QuestionCategory as QuestionCategoryModels;
use think\db\exception\ModelNotFoundException;

Class QuestionCategory {

    /**
     * 获取章节考点
     * @throws ModelNotFoundException
     * @return mixed
     */
    public function chapter(  )
    {
        $question = QuestionCategoryModels::with(['child'=>function($query){
            $query->with(['questions'=>function($query){
                $query->with(['doAnswer']);
            }]);
        }])->pid(2)->select();
        if ( $question->isEmpty() ) {
            throw new ModelNotFoundException('您访问的资源不存在');
        }
        foreach ( $question as $key => $_question ) {
            $question[$key]['done'] = 0;
            $question[$key]['count'] = 0;
            if ( $_question['child'] ) {
                foreach ( $_question['child'] as $_child_key => $_child ) {
                    $question[$key]['child'][$_child_key]['done'] = 0;
                    $question[$key]['child'][$_child_key]['count'] = 0;
                    if ( $_child['questions'] ) {
                        foreach ( $_child['questions'] as $_question_key => $_question ) {
                            $aid = [];
                            if ( $_question['do_answer'] ) {
                                foreach ( $_question['do_answer'] as $_do_answer ) {
                                    if ( ! in_array($_do_answer['aid'], $aid) ) {
                                        $aid[] = $_do_answer['aid'];
                                    }
                                }
                            }
                            $question[$key]['child'][$_child_key]['questions'][$_question_key]['done'] = count($aid);
                            $question[$key]['child'][$_child_key]['questions'][$_question_key]['count'] = Answer::where('qid', $_question['id'])->count();
                            $question[$key]['child'][$_child_key]['done'] += $question[$key]['child'][$_child_key]['questions'][$_question_key]['done']??0;
                            $question[$key]['child'][$_child_key]['count'] += $question[$key]['child'][$_child_key]['questions'][$_question_key]['count']??0;
                        }
                    }
                    $question[$key]['done'] += $question[$key]['child'][$_child_key]['done']??0;
                    $question[$key]['count'] += $question[$key]['child'][$_child_key]['count']??0;
                }
            }
        }
        return $question;
    }

}